package com.github.fork.spring;

import org.springframework.beans.factory.config.YamlProcessor.DocumentMatcher;
import org.springframework.beans.factory.config.YamlProcessor.MatchStatus;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Properties;
import java.util.Set;

/**
 * @author Jerry Liu
 * @since 2017/3/20
 */
public class ArrayDocumentMatcher implements DocumentMatcher {

    private final String key;

    private final String[] patterns;

    public ArrayDocumentMatcher(final String key, final String... patterns) {
        this.key = key;
        this.patterns = patterns;

    }

    @Override
    public MatchStatus matches(Properties properties) {
        if (!properties.containsKey(this.key)) {
            return MatchStatus.ABSTAIN;
        }
        Set<String> values = StringUtils
                .commaDelimitedListToSet(properties.getProperty(this.key));
        if (values.isEmpty()) {
            values = Collections.singleton("");
        }
        for (String pattern : this.patterns) {
            for (String value : values) {
                if (value.matches(pattern)) {
                    return MatchStatus.FOUND;
                }
            }
        }
        return MatchStatus.NOT_FOUND;
    }
}

